package org.example.java.util.concurrency;

/**
 * @author juntao zhang
 */
public class SleepInterrupt2 implements Runnable {

  public void run() {
    while (!Thread.currentThread().isInterrupted()) {
      sleep(100);
    }
    System.out.println("isInterrupted->" + Thread.currentThread().isInterrupted());
  }
  /*public void run() {
    try {
      System.out.println("in run() - about to sleep for 5 seconds");
//      Thread.currentThread().interrupt();
      Thread.sleep(5000);
      System.out.println("in run() - woke up");
    } catch (InterruptedException e) {
      System.out.println("in run() - interrupted while sleeping");
//      System.out.println(Thread.currentThread().isInterrupted());
      System.out.println("interrupted=>" + Thread.interrupted());
      //处理完中断异常后，返回到run（）方法人口，
      //如果没有return，线程不会实际被中断，它会继续打印下面的信息
      try {
        Thread.sleep(2000);
      } catch (InterruptedException e1) {
//        System.out.println(Thread.currentThread().isInterrupted());
        System.out.println("interrupted=>" + Thread.interrupted());
        System.out.println("in run() InterruptedException - interrupted while sleeping");
        return;
      }
      System.out.println("in run() InterruptedException - leaving normally");
      return;
    }
    System.out.println("in run() - leaving normally");
  }*/


  public static void main(String[] args) {
//    SleepInterrupt si = new SleepInterrupt();
//    Thread t = new Thread(si);
//    t.start();
//    //主线程休眠2秒，从而确保刚才启动的线程有机会执行一段时间
//    sleep(1000);
//    System.out.println("in main() - interrupting other thread");
//    //中断线程t
////    t.interrupt();
////    sleep(50);
////    System.out.println(t.isInterrupted());
////    System.out.println(t.isInterrupted());
//    sleep(50);
//    t.interrupt();
////    System.out.println(t.isInterrupted());
//    System.out.println("in main() - leaving");


    Thread sleepThread = new Thread() {
      @Override
      public void run() {
        try {
          Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
          System.out.println("have been interruptted....");
          Thread.currentThread().interrupt();
          yield();
          yield();
          yield();
          // in here this.isInterrupted() will return true
          System.out.println("now , instant interrupt flag : "
              + this.isInterrupted());
        }
      }
    };
    sleepThread.start();

    try {
      sleepThread.interrupt();
//      Thread.sleep( 1);
      Thread.yield();
      Thread.yield();
      Thread.yield();

      // in here ,why sleepThread.isInterrupted() return false ?
      System.out.println("sleep thread interrupt flag : "
          + sleepThread.isInterrupted());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void sleep(int i) {
    try {
      Thread.sleep(i);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
